package org.zls.client;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowResizeListener;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridRowListener;
import com.gwtext.client.widgets.layout.FitLayout;

public class CourseTable extends Composite {

	private Panel panel;
	private TabPanel tabs;
	private ResultTable grid;
	private Panel searchPanel;
	private static ColumnModel model;
	private static ColumnToggle toggle;

	public CourseTable() {

		panel = new Panel();
		tabs = new TabPanel();
		grid = new ResultTable();
		
		Button button = new Button("Change Columns", new ClickListener() {
			public void onClick(Widget sender) {
				toggle.center();
				toggle.onShow(model);
			}
		});
		
		searchPanel = new Panel();
		searchPanel.add(grid);
		searchPanel.add(button);
		searchPanel.setLayout(new FitLayout());
		
		addTab("Search", searchPanel, false);
		
		model = grid.getColumnModel();
		toggle = new ColumnToggle(grid, model);
		
		grid.addGridRowListener(new GridRowListener() {

			public void onRowClick(GridPanel grid, int rowIndex, EventObject e) {
				if (grid.getSelectionModel().isSelected(rowIndex)) {
					grid.getSelectionModel().deselectRow(rowIndex);
				} else {
					grid.getSelectionModel().selectRow(rowIndex, true);
				}
			}

			public void onRowContextMenu(GridPanel grid, int rowIndex,
					EventObject e) {
				if (grid.getSelectionModel().isSelected(rowIndex)) {
					grid.getSelectionModel().deselectRow(rowIndex);
				} else {
					grid.getSelectionModel().selectRow(rowIndex, true);
				}

			}

			public void onRowDblClick(GridPanel grid, int rowIndex,
					EventObject e) {
				addTab(grid.getStore().getRecordAt(rowIndex).getAsString("title"),
						new Panel(),
						true);
			}
		});

		Window.addWindowResizeListener(new WindowResizeListener() {

			public void onWindowResized(int width, int height) {
				panel.setWidth(width - 40);
				panel.doLayout();
			}
		});
		
		panel.setAutoHeight(true);
		searchPanel.setAutoHeight(true);
		panel.add(tabs);
		panel.setLayout(new FitLayout());
		initWidget(panel);
	}
	
    private Panel addTab(String title, Panel tab, boolean closable) {
        tab.setAutoScroll(true);
        tab.setTitle(title);
        tab.setClosable(closable);
        tabs.add(tab);
        return tab;
    }

	public void update(String query) {
		grid.update(query);
	}

	public void onShow() {
		grid.reconfigure(grid.getStore(), model);
		grid.setWidth(Window.getClientWidth() - 42);
		grid.doLayout();
	}
}
